package com.hhq.demo.controller;

import com.hhq.demo.mvc.ResponseBody;
import com.hhq.demo.mvc.ResponseView;
import com.hhq.demo.service.AdminService;
import com.hhq.demo.service.impl.AdminServiceImpl;
import com.hhq.demo.utils.JSONUtil;
import com.hhq.demo.utils.Message;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author HHQ
 * @date 2021年12月14日
 */
public class AdminController {

    AdminService adminService = new AdminServiceImpl();

    @ResponseBody("/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        boolean result = adminService.login(username, password);
        Message msg = null;
        if (result) {
            msg = new Message(0,"登录成功");
            //更新登录时间
            Date date = new Date();
            String ip = request.getRemoteAddr();
            adminService.updateLoginTime(username,date,ip);
            request.getSession().setAttribute("adminUsername",username);
        } else {
            msg = new Message(-1,"帐号或密码错误");
        }
        return JSONUtil.toJSON(msg);
    }

    @ResponseBody("/admin/getAdminInfo.do")
    public String getAdminInfo(HttpServletRequest request, HttpServletResponse response){
        return JSONUtil.toJSON(new Message(1,request.getSession().getAttribute("adminUsername")));
    }

    @ResponseBody("/admin/logout.do")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        request.getSession().invalidate();
        return JSONUtil.toJSON(new Message(1,"退出成功"));
    }
}
